<template>
    <div class="dashboard-container">
        <div class="app-container">
            <el-card shadow="never">
                <div class="header">
                    <span>{{ formType === 1 ? '试题录入' : '试题修改' }}</span>
                </div>
                <el-divider></el-divider>
                <div class="body">
                    <el-form :model="form" :rules="rules" ref="form">
                        <el-form-item label-width="68px" label="学科" prop="subjectID">
                            <el-select v-model="form.subjectID" placeholder="请选择学科">
                                <el-option
                                    v-for="item in subjectTypeList"
                                    :key="item.id"
                                    :label="item.subjectName"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label-width="68px" label="目录" prop="catalogID">
                            <el-select v-model="form.catalogID" placeholder="请选择目录">
                                <el-option
                                    v-for="item in catalogIDList"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label-width="68px" label="企业" prop="enterpriseID">
                            <el-select v-model="form.enterpriseID" placeholder="请选择企业">
                                <el-option
                                    v-for="item in enterpriseIDList"
                                    :key="item.id"
                                    :label="item.shortName"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label-width="68px" label="城市" prop="city" class="col-city is-required">
                            <el-select v-model="form.province" placeholder="请选择城市" @change="provinceChange">
                                <el-option
                                    v-for="item in provinceList"
                                    :key="item"
                                    :label="item"
                                    :value="item">
                                </el-option>
                            </el-select>
                            <el-select v-model="form.city" placeholder="请选择区县">
                                <el-option
                                    v-for="item in cityList"
                                    :key="item"
                                    :label="item"
                                    :value="item">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label-width="68px" label="方向" prop="direction">
                            <el-select v-model="form.direction" placeholder="请选择方向">
                                <el-option
                                    v-for="item in directionList"
                                    :key=item
                                    :label="item"
                                    :value="item">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label-width="68px" label="题型" prop="questionType">
                            <template>
                                <el-radio v-model="form.questionType" label="1">单选题</el-radio>
                                <el-radio v-model="form.questionType" label="2">多选题</el-radio>
                                <el-radio v-model="form.questionType" label="3">简答题</el-radio>
                            </template>
                        </el-form-item>
                        <el-form-item label-width="68px" label="难度" prop="difficulty">
                            <template>
                                <el-radio v-model="form.difficulty" label="1">简单</el-radio>
                                <el-radio v-model="form.difficulty" label="2">一般</el-radio>
                                <el-radio v-model="form.difficulty" label="3">困难</el-radio>
                            </template>
                        </el-form-item>
                        <el-form-item label-width="68px" label="题干" prop="question" class="is-required">
                            <quill-editor :options="editorOption" v-model="form.question" @blur="$refs.form.validateField('question')"></quill-editor>
                        </el-form-item>
                        <el-form-item label-width="68px" label="选项" prop="option" v-if="form.questionType !== '3'" class="is-required">
                            <el-checkbox-group v-model="rightOptionList">
                                <div class="option-item">
                                    <el-radio v-if="form.questionType === '1'" v-model="rightOption" label="1">A：</el-radio>
                                    <el-checkbox v-if="form.questionType === '2'" label="1">A：</el-checkbox>
                                    <el-input v-model="form.options[0].title"></el-input>
                                    <el-upload
                                        class="upload upload1"
                                        action=""
                                        accept=".jpg, .jpeg, .png"
                                        :show-file-list="false"
                                        :http-request="upload"
                                        :before-upload="beforeUpload">
                                        <el-button size="small" type="primary" @click="clickUploadBtn($event, 0)" plain>上传图片</el-button>
                                    </el-upload>
                                </div>
                                <div class="option-item">
                                    <el-radio v-if="form.questionType === '1'" v-model="rightOption" label="2">B：</el-radio>
                                    <el-checkbox v-if="form.questionType === '2'" label="2">B：</el-checkbox>
                                    <el-input v-model="form.options[1].title"></el-input>
                                    <el-upload
                                        class="upload upload1"
                                        action=""
                                        accept=".jpg, .jpeg, .png"
                                        :show-file-list="false"
                                        :http-request="upload"
                                        :before-upload="beforeUpload">
                                        <el-button size="small" type="primary" @click="clickUploadBtn($event, 1)" plain>上传图片</el-button>
                                    </el-upload>
                                </div>
                                <div class="option-item">
                                    <el-radio v-if="form.questionType === '1'" v-model="rightOption" label="3">C：</el-radio>
                                    <el-checkbox v-if="form.questionType === '2'" label="3">C：</el-checkbox>
                                    <el-input v-model="form.options[2].title"></el-input>
                                    <el-upload
                                        class="upload upload1"
                                        action=""
                                        accept=".jpg, .jpeg, .png"
                                        :show-file-list="false"
                                        :http-request="upload"
                                        :before-upload="beforeUpload">
                                        <el-button size="small" type="primary" @click="clickUploadBtn($event, 2)" plain>上传图片</el-button>
                                    </el-upload>
                                </div>
                                <div class="option-item">
                                    <el-radio v-if="form.questionType === '1'" v-model="rightOption" label="4">D：</el-radio>
                                    <el-checkbox v-if="form.questionType === '2'" label="4">D：</el-checkbox>
                                    <el-input v-model="form.options[3].title"></el-input>
                                    <el-upload
                                        class="upload upload1"
                                        action=""
                                        accept=".jpg, .jpeg, .png"
                                        :show-file-list="false"
                                        :http-request="upload"
                                        :before-upload="beforeUpload">
                                        <el-button size="small" type="primary" @click="clickUploadBtn($event, 3)" plain>上传图片</el-button>
                                    </el-upload>
                                </div>
                                <div class="option-img" v-if="!!((form.options.length !== 0 && form.options.every(e => !!e.img)) || optionImgList.length !== 0)">
                                    <div class="img-item" v-for="e in 4" :key="e" v-if="form.options[e - 1].img || optionImgList[e - 1]">
                                        <el-image
                                            @mouseenter="showImgClose($event, 1)"
                                            @mouseleave="showImgClose($event, 0)"
                                            :src="optionImgList[e - 1]"
                                            :preview-src-list="optionImgList">
                                        </el-image>
                                        <i
                                            class="el-icon-circle-close"
                                            @click="delImg(e)"
                                            @mouseenter="showImgClose($event, 1)"
                                            @mouseleave="showImgClose($event, 0)"></i>
                                        <div>{{ optionEn[e - 1] }}</div>
                                    </div>
                                </div>
                            </el-checkbox-group>
                        </el-form-item>
                        <el-form-item label-width="68px" label="视频" prop="videoURL" class="is-required">
                            <el-input v-model="form.videoURL" placeholder="请输入视频链接" @blur="$refs.form.validateField('videoURL')"></el-input>
                        </el-form-item>
                        <el-form-item label-width="68px" label="解析" prop="answer" class="is-required">
                            <quill-editor :options="editorOption" v-model="form.answer" @blur="$refs.form.validateField('answer')"></quill-editor>
                        </el-form-item>
                        <el-form-item label-width="68px" label="备注">
                            <el-input v-model="form.remarks" type="textarea" placeholder="请输入备注"></el-input>
                        </el-form-item>
                        <el-form-item label-width="68px" label="标签" prop="tags" class="is-required">
                            <el-select
                                v-model="checkedTags"
                                multiple
                                placeholder="请选择标签">
                                <el-option
                                    v-for="item in tagsList"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label-width="68px">
                            <el-button @click="clickBtn" type="primary"
                                       v-html="formType === 1 ? '添加试题' : '修改试题'"></el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </el-card>
        </div>
    </div>
</template>

<script>
import { getSubjectsList } from '@/api/hmmm/subjects'
import { direction } from '@/api/hmmm/constants'
import { getSimpleMenu } from '@/api/hmmm/directorys'
import { getCompanyList } from '@/api/hmmm/companys'
import { citys, provinces } from '@/api/hmmm/citys'
import { addQuestionItem, getQuestionItem, editQuestionItem } from '@/api/hmmm/questions'
import { getSimpleTags } from '@/api/hmmm/tags'
import COS from 'cos-js-sdk-v5'

export default {
    created () {
        this.back = !!this.$route.query.add
        this.$set(this.form, 'options', [
            { code: 'A', isRight: false },
            { code: 'B', isRight: false },
            { code: 'C', isRight: false },
            { code: 'D', isRight: false }
        ])
        this.backDisplay()
        this.getSubjectsList()
        this.getCompanyList()
    },
    data () {
        return {
            form: { questionType: '1', difficulty: '1' },
            formType: 1,
            back: false,
            subjectTypeList: [],
            catalogIDList: [],
            enterpriseIDList: [],
            provinceList: provinces(),
            cityList: [],
            directionList: direction,
            tagsList: [],
            checkedTags: [],
            rightOption: '',
            rightOptionList: [],
            optionImgList: [],
            optionEn: ['A', 'B', 'C', 'D'],
            currentUploadIndex: -1,
            rules: {
                subjectID: [
                    { required: true, message: '请选择学科', trigger: 'change' }
                ],
                catalogID: [
                    { required: true, message: '请选择目录', trigger: 'change' }
                ],
                enterpriseID: [
                    { required: true, message: '请选择企业', trigger: 'change' }
                ],
                city: [
                    { validator: (rule, value, callback) => {
                            if (!this.form.province || !this.form.city) {
                                return callback(new Error())
                            } else {
                                return callback()
                            }
                        }, message: '请选择城市与区县', trigger: 'change'
                    }
                ],
                direction: [
                    { required: true, message: '请选择方向', trigger: 'change' }
                ],
                questionType: [
                    { required: true, message: '请选择题型', trigger: 'change' }
                ],
                difficulty: [
                    { required: true, message: '请选择难度', trigger: 'change' }
                ],
                option: [
                    { validator: (rule, value, callback) => {
                            const flag1 = !this.rightOption
                            const flag2 = this.rightOptionList.length === 0
                            const inputFlag = !this.form.options.every(e => e.title)
                            if (inputFlag) {
                                return callback(new Error())
                            } else {
                                if (flag1 && this.form.questionType === '1') {
                                    return callback(new Error())
                                } else if (flag2 && this.form.questionType === '2') {
                                    return callback(new Error())
                                } else {
                                    return callback()
                                }
                            }
                        }, message: '请选择正确项并输入全部表单项', trigger: 'blur'
                    }
                ],
                question: [
                    { validator: (rule, value, callback) => {
                            const node = document.querySelectorAll('.quill-editor')
                            if (!this.form.question) {
                                node[0].classList.add('error-form')
                                return callback(new Error())
                            } else {
                                node[0].classList.remove('error-form')
                                return callback()
                            }
                        }, message: '请输入题干', trigger: 'blur'
                    }
                ],
                videoURL: [
                    { required: true, message: '请输入解析视频地址', trigger: 'change' }
                ],
                answer: [
                    { validator: (rule, value, callback) => {
                            const node = document.querySelectorAll('.quill-editor')
                            if (!this.form.answer) {
                                node[1].classList.add('error-form')
                                return callback(new Error())
                            } else {
                                node[1].classList.remove('error-form')
                                return callback()
                            }
                        }, message: '请输入答案解析', trigger: 'blur'
                    }
                ],
                tags: [
                    { validator: (rule, value, callback) => {
                            if (this.checkedTags.length < 1) return callback(new Error());
                            return callback()
                        }, message: '请选择标签', trigger: 'change'
                    }
                ]
            },
            editorOption: {
                modules: {
                    toolbar: [
                        ['bold', 'italic', 'underline', 'strike'], //加粗，斜体，下划线，删除线
                        ['blockquote', 'code-block'], //引用，代码块
                        [{ 'header': 1 }, { 'header': 2 }], // 标题，键值对的形式；1、2表示字体大小
                        [{ 'list': 'ordered' }, { 'list': 'bullet' }], //列表
                        [{ 'script': 'sub' }, { 'script': 'super' }], // 上下标
                        [{ 'indent': '-1' }, { 'indent': '+1' }], // 缩进
                        [{ 'color': [] }, { 'background': [] }], // 字体颜色，字体背景颜色
                        [{ 'align': [] }] //对齐方式
                    ]
                },
                placeholder: ''
            }
        }
    },
    methods: {
        async backDisplay () {
            if (this.$route.query.id) {
                this.formType = 2
                const res = await getQuestionItem({
                    id: this.$route.query.id
                })
                this.form = res.data
                if (this.form.questionType === '1') {
                    this.form.options.forEach((e, i) => {
                        if (e.isRight) this.rightOption = i + 1 + ''
                    })
                } else if (this.form.questionType === '2') {
                    this.form.options.forEach((e, i) => {
                        if (e.isRight) this.rightOptionList.push(i + 1 + '')
                    })
                }
                this.checkedTags = this.form.tags.split(',').map(e => e === 'undefined' ? undefined : +e).filter(e => !!e)
            } else {
                this.formType = 1
            }
            this.optionImgList = this.form.options.map(e => e.img)
        },
        async getSubjectsList () {
            const res = await getSubjectsList()
            this.subjectTypeList = res.data.items
        },
        async getSimpleMenu () {
            const res = await getSimpleMenu({
                subjectID: this.form.subjectID
            })
            this.catalogIDList = res.data
        },
        async getCompanyList () {
            const res = await getCompanyList()
            this.enterpriseIDList = res.data.items
        },
        async getSimpleTags () {
            const res = await getSimpleTags({
                subjectID: this.form.subjectID
            })
            this.tagsList = res.data
        },
        upload (e) {
            const file = e.file
            const cos = new COS({
                SecretId: 'AKIDqdO1PZT9bpskSBoIl9QZUQKBqHjxxkWA',
                SecretKey: 'Z1GLGhy3ywglfMwKUP8yhBbwGSRNB3kH'
            })
            cos.putObject({
                Bucket: 'cheng-1315032601',
                Region: 'ap-shanghai',
                Key: e.file.name,
                StorageClass: 'STANDARD',
                Body: file
            }, (err, data) => {
                if (data.statusCode === 200 && data.Location) {
                    this.$message.success('上传成功')
                    if (this.currentUploadIndex >= 0) this.optionImgList[this.currentUploadIndex] = 'https://' + data.Location
                    this.form.options = this.form.options.map((e, i) => {
                        this.optionImgList[i] ? e.img = this.optionImgList[i] : ''
                        return e
                    })
                } else {
                    this.$message.error(err.Message)
                }
            })
        },
        beforeUpload (file) {
            const isJPG = file.type === 'image/jpeg'
            const isPNG = file.type === 'image/png'
            const isLt2M = file.size / 1024 / 1024 < 2
            if (!(isJPG || isPNG)) {
                this.$message.error('上传图片只能是 JPG 或 PNG 格式！')
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!')
            }
            return (isJPG || isPNG) && isLt2M
        },
        clickUploadBtn (e, i) {
            e.target.blur()
            e.target.parentNode.blur()
            this.currentUploadIndex = i
        },
        showImgClose (e, o) {
            if (e.target.nodeName === 'IMG') e.target.parentNode.nextElementSibling.style.opacity = o
            if (e.target.nodeName === 'I') e.target.style.opacity = o
        },
        delImg (i) {
            this.optionImgList.splice(i - 1, 1, '')
            this.form.options[i - 1].img = ''
        },
        clickBtn () {
            this.$refs.form.validate(async valid => {
                if (valid) {
                    if (this.form.questionType === '1') {
                        this.form.options[+this.rightOption - 1].isRight = true
                    } else if (this.form.questionType === '2') {
                        this.rightOptionList.forEach(e => this.form.options[+e - 1].isRight = true)
                    } else {
                        this.form.options.forEach(e => e.title = 'null')
                    }
                    this.form.tags = this.checkedTags.join(',')
                    if (this.formType === 1) {
                        const res = await addQuestionItem(this.form)
                        if (res.data.id) {
                            this.reset()
                            this.$message.success('添加成功')
                            if (this.back) this.$router.back()
                        }
                    } else {
                        const res = await editQuestionItem(this.form)
                        if (res.data.success) {
                            this.$message.success('修改成功')
                            await this.$router.back()
                        }
                    }
                }
            })
        },
        provinceChange () {
            this.$set(this.form, 'city', '')
        },
        reset () {
            this.form = { questionType: '1', difficulty: '1' }
            this.rightOption = ''
            this.rightOptionList = []
            this.checkedTags = []
            this.optionImgList = []
            this.$set(this.form, 'options', [
                { code: 'A', isRight: false },
                { code: 'B', isRight: false },
                { code: 'C', isRight: false },
                { code: 'D', isRight: false }
            ])
            this.$refs.form.resetFields()
        }
    },
    watch: {
        'form.province': {
            handler (val) {
                this.cityList = citys(val)
            }
        },
        'form.subjectID': {
            deep: true,
            handler (val) {
                if (val) {
                    this.getSimpleMenu()
                    this.getSimpleTags()
                }
            }
        }
    }
}
</script>

<style scoped lang="scss">
.dashboard-container {
    .app-container {
        padding: 5px 10px;

        ::v-deep .el-card__body {
            padding: 0;

            .header {
                padding-top: 20px;

                span {
                    font-size: 16px;
                    margin: 20px 20px 0;
                }
            }
        }

        .body {
            padding: 20px 50px;

            .option-item {
                display: flex;
                align-items: center;
                height: 50px;

                .el-radio {
                    margin-right: 0;
                }

                .upload {
                    margin-left: 20px;

                    ::v-deep .el-upload {
                        display: flex;
                        align-items: center;

                        .el-button {
                            height: 36px;
                        }
                    }
                }

                ::v-deep .el-input {
                    width: auto;

                    .el-input__inner {
                        width: 300px !important;
                    }
                }
            }

            .option-img {
                display: flex;
                padding-top: 7px;

                .img-item {
                    line-height: 0;
                    position: relative;
                    overflow: hidden;
                    margin-right: 6px;

                    div:last-of-type {
                        color: #606266;
                        height: 14px;
                        font-size: 14px;
                        line-height: 14px;
                        text-align: center;
                        margin-top: 8px;
                    }

                    i {
                        position: absolute;
                        font-size: 20px;
                        border-radius: 10px;
                        color: #FFFFFF;
                        right: 4px;
                        top: 4px;
                        background-color: rgba(0, 0, 0, 0.15);
                        box-shadow: 0 0 30px 16px rgba(0, 0, 0, 0.2);
                        cursor: pointer;
                        opacity: 0;
                        transition: all 0.15s;

                        &:hover {
                            color: #F56C6C;
                        }
                    }

                    ::v-deep .el-image {
                        width: 107px !important;
                        height: 107px !important;

                        img {
                            border: 1px solid #DCDFE6;
                            border-radius: 4px;
                        }
                    }
                }
            }

            ::v-deep .el-form {
                .col-city .el-select {
                    margin-right: 4px;

                    .el-input__inner {
                        width: 172px;
                    }
                }

                .el-input__inner {
                    width: 348px;
                }

                textarea {
                    width: 348px;
                }

                .quill-editor {
                    > div {
                        border: 1px solid #DCDFE6;
                    }

                    div:first-of-type {
                        border-radius: 4px 4px 0 0;
                    }

                    div:last-of-type {
                        border-radius: 0 0 4px 4px;
                        border-top: none;
                    }
                }

                .error-form {
                    > div {
                        border: 1px solid #F56C6C;
                    }
                }
            }
        }

        .el-divider {
            margin: 20px 0;
        }
    }

    ::v-deep .el-dialog {
        .el-dialog__header {
            padding: 0;
        }

        .el-dialog__body {
            display: flex;
            padding: 0;

            img {
                border-radius: 8px;
            }
        }
    }
}
</style>
